<?php

class FeedbackController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
    	 public function filters()
	{
		return array(
			'accessControl',
		);
	}

	public function accessRules()
	{
		return array(
			array('allow',
			      'actions' => array('login'),
			      'users' => array('*'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('index,answer'),
				'roles'=>array('user'),
			),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('index','edit','delete','print', 'report'),
				'roles'=>array('admin'),
			),
			array('deny',
                   'actions' =>array('edit', 'delete', 'print'),
			       'roles' => array('user'),
			),
		);
	}

	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	public function actionIndex()
	{
		$this->pagetitle = 'Обращения в интернет-приемной - '.Yii::app()->name;
		$criteria = new CDbCriteria;
       $criteria->condition = 'status_id >= 1';
        if(Yii::app()->user->role == 'user'){
            $criteria->condition = "user_id=:id";
            $criteria->condition = "status_id=2";
            $criteria->params = array(':id'=> Yii::app()->user->id);
        }
		$criteria->order = 'data DESC';
		$model = Obrasheniya::model()->findAll($criteria);
		$this->render('list', array('model'=>$model));
	}

    public function actionView($id)
    {
        $model = News::model()->findByPk($id);
        $this->pagetitle = $model->title.' - '.Yii::app()->name;
        $this->render('view', array('model' => $model));
    }

    public function actionAdd()
    {
        $model = new News;
        if(isset($_POST['news']))
        {
            $model->attributes = $_POST['news'];
            $model->type = 0;
            $model->date_public = date('Y.m.d h:i:s',strtotime($model->date_public));
            $model->file = CUploadedFile::getInstance($model,'file');
            if($model->validate())
            {
                if(isset($model->file))
                {
                    $file_name = $this->uniqueName($model->file->name);
                    $model->file->saveAs(dirname(Yii::app()->getBasePath()) .'/uploads/' . $file_name);
                    $model->file = $file_name;
                }
                $model->save();
                $this->redirect(array('/news'));
            }
        }
        $this->render('form', array('model' => $model));
    }

    public function actionEdit($id)
    {
        $model = Obrasheniya::model()->findByPk($id);
        if($_POST['Obrasheniya']['user_id']!=null){
            $model->user_id = $_POST['Obrasheniya']['user_id'];
            $model->data_reg = date('Y-m-d h:i:s',time());
			$model->status_id = 2;
            $model->save(false);
        }
         if($_POST['Obrasheniya']['answer']!=null){
            $model->answer = $_POST['Obrasheniya']['answer'];
            $model->date_isp = date('Y-m-d h:i:s',time());
            $model->status_id = 3;
            if($model->save(false)){
                $this->sendEmail($model->id);
                $this->redirect(array('/feedback'));
            }
         }

        $this->render('form', array('model' => $model));

    }

    public function actionDelete($id)
    {
        $model = Obrasheniya::model()->findByPk($id);
        if(isset($model->file) AND $model->file!=null)
        {
            @unlink(dirname(Yii::app()->getBasePath()) .'/uploads/' . $model->file);
        }
        Obrasheniya::model()->deleteByPk($id);
        $this->redirect(array('/feedback'));
    }

    public function actionAnswer($id){
        $model = Obrasheniya::model()->findByPk($id);
        if($_POST['Obrasheniya']['answer']!=null){
            $model->answer = $_POST['Obrasheniya']['answer'];
            $model->date_isp = date('Y-m-d h:i:s',time());
            $model->status_id = 3;
            if($model->save(false)){
                $this->sendEmail($model->id);
                $this->redirect(array('/feedback'));
            }
         }
        $this->render('aform', array('model' => $model));
    }

    private function uniqueName($fname)
	{
		$ext = end(explode(".",$fname));
		return md5(uniqid()).'.'.$ext;
	}

    public function actionPrint($id)
    {
        $model = Obrasheniya::model()->findByPk($id);
        $this->renderPartial('printobr', array('model' => $model));

    }

    public function actionReport()
    {
        $criteria = new CDbCriteria;
        $criteria->condition = 'status_id>=1';
        $criteria->addCondition("data >= '".date('Y-m-d h:i:s',strtotime($_POST['date1']))."'");
        $model = Obrasheniya::model()->findAll($criteria);
        $this->renderPartial('report', array(
                                            'date1' => $_POST['date1'],
                                            'date2' => $_POST['date2'],
                                            'model' => $model
                                       ));
    }

    private function sendEmail($id){
        $mail = new Mail;
        $subject = 'Ответ на Ваше обращение на сайте obrazovaniestr.ru';

        $model = Obrasheniya::model()->findByPk($id);
        
        $mail->subject = $subject;
        $mail->to = $model->email;

        $body = '<h3>Ответ на обращение гр. '.$model->lastname.' '.$model->firstname.' '.$model->middlename.' по теме "'.$model->theme.'", присланное '.date('d.m.Y',strtotime($model->data)).', зарегистрированное '.date('d.m.Y',strtotime($model->data_reg)).'</h3>';
        $body.= $model->answer;
        $body.= '<p>'.$model->user->fio.'</p><p>'.date('d.m.Y',time()).'</p>';
        $mail->html = $body;
        $mail->from = 'strelitamakgorono@gmail.com';

        $res = $mail->Send();
        return $res;
    }


}